package com.krui.iweibo.service.imageprocess;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import com.krui.iweibo.utils.MD5Utils;

public class ImageManager {
	
	
	private Context context;

	Map<String, SoftReference<Bitmap>> imgCache;

	public ImageManager(Context context) {
		this.context = context;
		imgCache = new HashMap<String, SoftReference<Bitmap>>();
	}

	
	/**
	 * 得到需要加载的图片
	 * @param url 图片网络地址
	 * @param context
	 * @return
	 */
	public Bitmap safeGet(String url){
		
		//先从文件中查找图片
		Bitmap bitmap = getFromFileSys(url);
		
		//如果找到就放map缓存
		if (bitmap != null) {
			synchronized (this) {
				imgCache.put(url, new SoftReference<Bitmap>(bitmap));
			}
			
			return bitmap;
		}
		
		return downLoadFromUrl(url);
	}
	
	
	
	
	/**
	 * 
	 * 判断缓存种是否含有图片
	 * */
	public boolean isHaveInCache(String url) {

		return imgCache.containsKey(url);
	}

	/**
	 * 从缓存中读取图片
	 * 
	 * @param url
	 * @return
	 */
	public Bitmap getFromCache(String url) {
		Bitmap bitmap = null;

		bitmap = this.getFromMapCache(url);

		if (bitmap == null) {
			bitmap = getFromFileSys(url);
		}

		return bitmap;
	}

	/**
	 * 从map缓存中读取图片
	 * 
	 * @param url
	 * @return
	 */
	public Bitmap getFromMapCache(String url) {
		
		Bitmap bitmap = null;
		
		SoftReference<Bitmap> imgReference = null;
		
		synchronized (this) {
			imgReference = imgCache.get(url);
		}

		if (imgReference != null) {
			bitmap = imgReference.get();
		}

		if (bitmap != null) {
			return bitmap;
		}

		return bitmap;
	}

	/**
	 * 从文件缓存读取图片
	 * 
	 * @param url
	 * @return 
	 */
	private Bitmap getFromFileSys(String url) {
		
		String fileName = getMD5String(url);
		FileInputStream fis = null;
		try {
			fis = context.openFileInput(fileName);
			return BitmapFactory.decodeStream(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		finally{
			if (fis != null) {
				try {fis.close();} catch (Exception e2) {}
			}
		}
	}

	/**
	 * 从网络下载图片并缓存到本地
	 * @param url
	 */
	public Bitmap downLoadFromUrl(String imgUrl){
		try {
			URL url = new URL(imgUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			
			InputStream is = connection.getInputStream();
			
			String  fileName = write2Cache(getMD5String(imgUrl),is);
			
			return BitmapFactory.decodeFile(fileName);
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("IO error");
			return null;
		}
		
	}
	
	
	
	/**
	 * 将图片保存到cache,手机所在包data下面
	 * @param context
	 * @param filaName
	 * @param is
	 */
	private String write2Cache(String fileName, InputStream is) {
		
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(context.openFileOutput(fileName, Context.MODE_PRIVATE));
			
			byte[] buf = new byte[1024];
			int len = 0;
			while((len = bis.read(buf)) != -1){
				bos.write(buf, 0, len);
			}
			
		} catch (Exception e) {
			
		}finally{
			if (bis != null) {
				try{bis.close();}catch (Exception e) { }
			}
			
			if (bos != null) {
				try{bos.close();}catch (Exception e) { }
			}
		}
		
		return context.getFilesDir() + "/" + fileName;
		
	}

	private String getMD5String(String str) {
		return MD5Utils.getMD5String(str);
	}
	
	
	

}
